﻿using System;
using System.Data;
using System.Collections;
using System.Threading;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Co = Code.Models;
using Code.Commen;
using Code.BLL;

using Op = OpenCode;

namespace QianBuo.Lottery.Server
{

    internal class OpenWin
    {
        public OpenWin(Co.Lottery lottery, Co.Issue issue)
        {
            if (lottery == null)
                throw new ArgumentNullException("lottery");
            if (issue == null)
                throw new ArgumentNullException("issue");

            this.lottery = lottery;
            this.issue = issue;
        }
        private Co.Lottery lottery;
        private Co.Issue issue;
        private IssueManage IM = new IssueManage();
        private SchemeManage SM = new SchemeManage();
        /// <summary>
        /// 日志记录
        /// </summary>
        private log4net.ILog Log = Code.Commen.Log.GetLog(typeof(OpenWin));

        /// <summary>
        /// 对指定的期开奖
        /// </summary>
        /// <param name="type">彩种</param>
        /// <param name="cuopen">要开的期</param>
        public void DoOpen()
        {
            int time = (int)((this.lottery.OpenWinDelayTime - (DateTime.Now - issue.EndTime).TotalSeconds) * 1000);
            if (time > 0)
                Thread.Sleep(time);

            var doTime = DateTime.Now;
            int errorcount = 0;
            do
            {
                try
                {
                    var open = Op.Lottery.CreateLottery(this.lottery.ID);

                    var tmpIssue = open.GetCurrentWin(issue.FormatIssueName, issue.EndTime);

                    if (tmpIssue != null)
                    {
                        if (Log.IsDebugEnabled)
                            Log.Debug(string.Format("{0}第{1}期开奖:{2}", this.lottery.Alias, tmpIssue.Number, tmpIssue.WinNumber));

                        if (tmpIssue.IsNull)
                        {
                            if (Log.IsInfoEnabled)
                                Log.Info(string.Format("{0}第{1}期开奖遗漏！", this.lottery.Alias, issue.FormatIssueName));
                            break;
                        }
                        int rs = 0;
                        if (tmpIssue.LotteryID == this.lottery.ID)
                        {
                            rs = IM.Update(new { OpenCode = tmpIssue.WinNumber, State = (short)Co.IssueState.Opened }, new { issue.ID, State = (short)Co.IssueState.Normal });
                        }
                        else 
                        {
                            break;
                        }
                       

                        if (rs >= 0)
                        {
                            while (SM.Select(s => s.Where(p => p.IssueID == issue.ID && p.State == (short)Co.SchemeState.Normal).Count() > 0))
                                Thread.Sleep(3000);

                            SM.OpenWin(issue.ID);
                            return; //开奖成功
                        }
                    }
                    Thread.Sleep(500);
                    if ((DateTime.Now - doTime).TotalSeconds > this.lottery.OpenWinOverTime)
                    {
                        if (Log.IsInfoEnabled)
                            Log.Info(string.Format("{0}第{1}期开奖出错:延迟超过{2}s", this.lottery.Alias, this.issue.FormatIssueName, this.lottery.OpenWinOverTime));
                        else if (Log.IsWarnEnabled)
                            Log.Warn(string.Format("{0}第{1}期开奖出错:延迟超过{2}s", this.lottery.Alias, this.issue.FormatIssueName, this.lottery.OpenWinOverTime));
                        break;
                    }
                }
                catch (Exception e)
                {
                    errorcount++;
                    if (errorcount > 5)
                    {
                        if (Log.IsDebugEnabled)
                            Log.Debug(string.Format("{0}第{1}期开奖出错", this.lottery.Alias, this.issue.FormatIssueName), e);
                        else if (Log.IsInfoEnabled)
                            Log.Info(string.Format("{0}第{1}期开奖出错:{2}", this.lottery.Alias, this.issue.FormatIssueName, e.Message));
                        else if (Log.IsErrorEnabled)
                            Log.Error(string.Format("{0}第{1}期开奖出错:{2}", this.lottery.Alias, this.issue.FormatIssueName, e.Message));
                        break;
                    }
                }
            } while (true);
            
            //开奖失败
            if(CacheManage.OptionSite[Co.Option_Site_Key.Site_Lottery_AutoCancleTimeOutScheme].ToBool(false))
                SM.CancleTimeOutSchemes(issue.ID);

        }
    }
}
